<template>
  <div class="vaccine-container">
    <!-- 左侧：顾客信息和疫苗/驱虫单列表 -->
    <div class="left-panel">
      <!-- 宠物信息 -->
      <div v-if="selectedPet" class="pet-info-section">
        <div class="pet-tab">
          <span class="pet-name"
            >{{ selectedPet.name }}({{ selectedPet.ownerName }})</span
          >
          <a-button type="text" size="small" @click="closePetTab">×</a-button>
        </div>

        <div class="pet-details">
          <div class="detail-row">
            <span class="label">主人：</span>
            <span class="value">{{ selectedPet.ownerName }}</span>
          </div>
          <div class="detail-row">
            <span class="label">电话：</span>
            <span class="value">{{ selectedPet.ownerPhone }}</span>
          </div>
          <div class="detail-row">
            <span class="label">种类：</span>
            <span class="value">{{ selectedPet.type }}</span>
          </div>
          <div class="detail-row">
            <span class="label">品种：</span>
            <span class="value">{{ selectedPet.breed || '未知' }}</span>
          </div>
          <div class="detail-row">
            <span class="label">性别：</span>
            <span class="value">{{ selectedPet.gender || '未知' }}</span>
          </div>
          <div class="detail-row">
            <span class="label">年龄：</span>
            <span class="value">{{ selectedPet.age || '未知' }}</span>
          </div>
          <div class="detail-row">
            <span class="label">绝育：</span>
            <span class="value">{{ selectedPet.neutered || '未知' }}</span>
          </div>
        </div>
      </div>

      <!-- 疫苗/驱虫单列表 -->
      <div v-if="selectedPet" class="vaccine-orders-section">
        <h3>疫苗/驱虫单</h3>
        <div class="orders-list">
          <div
            v-for="order in vaccineOrders"
            :key="order.id"
            class="order-item"
            :class="{ active: selectedOrder?.id === order.id }"
            @click="selectOrder(order)"
          >
            <div class="order-info">
              <span class="order-name">{{ order.orderName }}</span>
              <span class="order-time">{{ order.createTime }}</span>
            </div>
            <div class="order-status">
              <a-tag :color="order.status === 'pending' ? 'orange' : 'green'">
                {{ order.status === 'pending' ? '待完成' : '已完成' }}
              </a-tag>
            </div>
          </div>
        </div>

        <!-- 添加服务单按钮 -->
        <div class="add-order-buttons">
          <a-button
            type="primary"
            block
            @click="createVaccineOrder"
            class="add-vaccine-btn"
          >
            + 疫苗单
          </a-button>
          <a-button
            type="primary"
            block
            @click="createDewormingOrder"
            class="add-deworming-btn"
          >
            + 驱虫单
          </a-button>
        </div>
      </div>

      <!-- 未选择宠物时的提示 -->
      <div v-else class="no-selection">
        <div class="empty-state">
          <div class="empty-icon">💉</div>
          <h3>请选择宠物</h3>
          <p>从右侧列表中选择一个宠物来创建疫苗/驱虫服务单</p>
        </div>
      </div>
    </div>

    <!-- 中间：疫苗/驱虫录入界面 -->
    <div class="center-panel">
      <div v-if="selectedOrder" class="vaccine-form">
        <!-- 表单头部 -->
        <div class="form-header">
          <div class="header-left">
            <h2>
              {{ selectedOrder.orderType === 'vaccine' ? '疫苗单' : '驱虫单' }}
            </h2>
            <span class="create-time"
              >创建时间: {{ selectedOrder.createTime }}</span
            >
          </div>
          <div class="header-right">
            <a-button
              type="default"
              @click="printOrder"
              style="margin-right: 8px"
              title="打印"
            >
              🖨️
            </a-button>
            <a-button type="primary" @click="saveOrder">保存</a-button>
          </div>
        </div>

        <!-- 疫苗/驱虫计划 -->
        <div class="vaccine-schedule">
          <h3>
            {{
              selectedOrder.orderType === 'vaccine' ? '免疫计划' : '驱虫计划'
            }}
          </h3>
          <div class="schedule-list">
            <div
              v-for="(dose, index) in selectedOrder.doses"
              :key="index"
              class="dose-item"
              :class="{ completed: dose.completed }"
            >
              <div class="dose-header">
                <div class="dose-info">
                  <span class="dose-name">{{ dose.name }}</span>
                  <span class="dose-date">{{ dose.scheduledDate }}</span>
                </div>
                <div class="dose-status">
                  <a-switch
                    v-model:checked="dose.completed"
                    @change="handleDoseStatusChange(dose, index)"
                  />
                  <span class="status-text">{{
                    dose.completed ? '已完成' : '待完成'
                  }}</span>
                </div>
              </div>

              <!-- 剂量详情 -->
              <div v-if="dose.completed" class="dose-details">
                <div class="detail-row">
                  <span class="label">免疫日期：</span>
                  <a-date-picker
                    v-model:value="dose.actualDate"
                    format="YYYY-MM-DD"
                    style="width: 150px"
                  />
                </div>
                <div class="detail-row">
                  <span class="label">体温：</span>
                  <a-input-number
                    v-model:value="dose.temperature"
                    :min="0"
                    :max="50"
                    style="width: 100px"
                  />
                  <span class="unit">℃</span>
                </div>
                <div class="detail-row">
                  <span class="label">体重：</span>
                  <a-input-number
                    v-model:value="dose.weight"
                    :min="0"
                    :max="100"
                    :precision="2"
                    style="width: 100px"
                  />
                  <span class="unit">kg</span>
                </div>
                <div class="detail-row">
                  <span class="label">主治医生：</span>
                  <a-input v-model:value="dose.doctor" style="width: 150px" />
                </div>
                <div class="detail-row">
                  <span class="label">备注：</span>
                  <a-input v-model:value="dose.remarks" style="width: 300px" />
                </div>

                <!-- 商品列表 -->
                <div class="products-section">
                  <div class="section-header">
                    <h4>商品列表</h4>
                    <a-button
                      type="primary"
                      size="small"
                      @click="addProduct(dose)"
                    >
                      + 添加商品
                    </a-button>
                  </div>
                  <a-table
                    :columns="productColumns"
                    :data-source="dose.products"
                    :pagination="false"
                    size="small"
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.key === 'total'">
                        ¥{{ (record.unitPrice * record.quantity).toFixed(2) }}
                      </template>
                      <template v-else-if="column.key === 'action'">
                        <a-button
                          type="text"
                          size="small"
                          danger
                          @click="removeProduct(dose, record)"
                        >
                          删除
                        </a-button>
                      </template>
                    </template>
                  </a-table>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 合计 -->
        <div class="total-section">
          <span class="total-label">合计：</span>
          <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 未选择订单时的提示 -->
      <div v-else class="no-order-selected">
        <div class="empty-state">
          <div class="empty-icon">📋</div>
          <h3>请选择或创建疫苗/驱虫单</h3>
          <p>从左侧列表中选择一个订单或创建新的服务单</p>
        </div>
      </div>
    </div>

    <!-- 右侧：宠物选择面板 -->
    <div class="right-panel">
      <PetSelector
        :pets="pets"
        :selected-pet="selectedPet"
        :active-tab="activeTab"
        title="选择宠物"
        @update:selected-pet="selectPet"
        @update:active-tab="activeTab = $event"
        @search="searchPets"
      />
    </div>

    <!-- 添加商品模态框 -->
    <ProductModal
      :visible="showProductModal"
      :dose="currentDose"
      @update:visible="showProductModal = $event"
      @success="handleProductSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

import PetSelector from '../components/PetSelector.vue';
import ProductModal from './components/ProductModal.vue';

// 接口定义
interface Pet {
  id: string;
  name: string;
  type: string;
  age?: string;
  breed?: string;
  gender?: string;
  neutered?: string;
  ownerName: string;
  ownerPhone: string;
  contact: string;
  doctor: string;
  phone: string;
}

interface Product {
  id: string;
  name: string;
  specification: string;
  unit: string;
  unitPrice: number;
  quantity: number;
  addedBy: string;
}

interface Dose {
  name: string;
  scheduledDate: string;
  completed: boolean;
  actualDate?: any;
  temperature?: number;
  weight?: number;
  doctor?: string;
  remarks?: string;
  products: Product[];
}

interface VaccineOrder {
  id: string;
  orderName: string;
  orderType: 'vaccine' | 'deworming';
  createTime: string;
  status: 'pending' | 'completed';
  petId: string;
  doses: Dose[];
}

// 响应式数据
const selectedPet = ref<Pet | null>(null);
const selectedOrder = ref<VaccineOrder | null>(null);
const vaccineOrders = ref<VaccineOrder[]>([]);
const activeTab = ref('today');
const showProductModal = ref(false);
const currentDose = ref<Dose | null>(null);

// 模拟宠物数据
const pets = ref<Pet[]>([
  {
    id: 'P001',
    name: '球球',
    type: '狗',
    age: '3',
    breed: '金毛',
    gender: '公',
    neutered: '否',
    ownerName: '赵女士',
    ownerPhone: '18300138001',
    contact: '18300138001',
    doctor: '孙医生',
    phone: '18300138001',
  },
  {
    id: 'P002',
    name: '兜兜',
    type: '猫',
    age: '2',
    breed: '英短',
    gender: '未知',
    neutered: '否',
    ownerName: '王先生',
    ownerPhone: '18243535',
    contact: '18243535',
    doctor: '孙医生',
    phone: '18243535',
  },
]);

// 商品表格列定义
const productColumns = [
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '规格', dataIndex: 'specification', key: 'specification' },
  { title: '单位', dataIndex: 'unit', key: 'unit' },
  { title: '单价', dataIndex: 'unitPrice', key: 'unitPrice' },
  { title: '数量', dataIndex: 'quantity', key: 'quantity' },
  { title: '合计', key: 'total' },
  { title: '添加人', dataIndex: 'addedBy', key: 'addedBy' },
  { title: '操作', key: 'action' },
];

// 计算属性
const totalAmount = computed(() => {
  if (!selectedOrder.value) return 0;
  return selectedOrder.value.doses.reduce((total, dose) => {
    return (
      total +
      dose.products.reduce((doseTotal, product) => {
        return doseTotal + product.unitPrice * product.quantity;
      }, 0)
    );
  }, 0);
});

// 方法
const selectPet = (pet: Pet | null) => {
  if (!pet) return;
  selectedPet.value = pet;
  selectedOrder.value = null;
  loadVaccineOrders(pet.id);
};

const closePetTab = () => {
  selectedPet.value = null;
  selectedOrder.value = null;
  vaccineOrders.value = [];
};

const loadVaccineOrders = (petId: string) => {
  // 模拟加载疫苗/驱虫单
  vaccineOrders.value = [
    {
      id: '1',
      orderName: '基础疫苗',
      orderType: 'vaccine',
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      status: 'pending',
      petId: petId,
      doses: [
        {
          name: '首免',
          scheduledDate: dayjs().format('YYYY-MM-DD'),
          completed: true,
          actualDate: dayjs(),
          temperature: 38.2,
          weight: 4.5,
          doctor: '孙医生',
          remarks: '基础疫苗首免',
          products: [],
        },
        {
          name: '二免',
          scheduledDate: dayjs().add(21, 'day').format('YYYY-MM-DD'),
          completed: false,
          products: [],
        },
        {
          name: '三免',
          scheduledDate: dayjs().add(42, 'day').format('YYYY-MM-DD'),
          completed: false,
          products: [],
        },
        {
          name: '四免',
          scheduledDate: dayjs().add(49, 'day').format('YYYY-MM-DD'),
          completed: false,
          products: [],
        },
      ],
    },
  ];

  // 默认选择最新的疫苗单
  if (vaccineOrders.value.length > 0) {
    selectOrder(vaccineOrders.value[0]);
  }
};

const createVaccineOrder = () => {
  if (!selectedPet.value) {
    message.warning('请先选择宠物');
    return;
  }

  const newOrder: VaccineOrder = {
    id: Date.now().toString(),
    orderName: '基础疫苗',
    orderType: 'vaccine',
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    status: 'pending',
    petId: selectedPet.value.id,
    doses: [
      {
        name: '首免',
        scheduledDate: dayjs().format('YYYY-MM-DD'),
        completed: false,
        products: [],
      },
      {
        name: '二免',
        scheduledDate: dayjs().add(21, 'day').format('YYYY-MM-DD'),
        completed: false,
        products: [],
      },
      {
        name: '三免',
        scheduledDate: dayjs().add(42, 'day').format('YYYY-MM-DD'),
        completed: false,
        products: [],
      },
      {
        name: '四免',
        scheduledDate: dayjs().add(49, 'day').format('YYYY-MM-DD'),
        completed: false,
        products: [],
      },
    ],
  };

  vaccineOrders.value.unshift(newOrder);
  selectOrder(newOrder);
  message.success('新建疫苗单成功！');
};

const createDewormingOrder = () => {
  if (!selectedPet.value) {
    message.warning('请先选择宠物');
    return;
  }

  const newOrder: VaccineOrder = {
    id: Date.now().toString(),
    orderName: '驱虫服务',
    orderType: 'deworming',
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    status: 'pending',
    petId: selectedPet.value.id,
    doses: [
      {
        name: '首次驱虫',
        scheduledDate: dayjs().format('YYYY-MM-DD'),
        completed: false,
        products: [],
      },
      {
        name: '二次驱虫',
        scheduledDate: dayjs().add(30, 'day').format('YYYY-MM-DD'),
        completed: false,
        products: [],
      },
    ],
  };

  vaccineOrders.value.unshift(newOrder);
  selectOrder(newOrder);
  message.success('新建驱虫单成功！');
};

const selectOrder = (order: VaccineOrder) => {
  selectedOrder.value = order;
};

const handleDoseStatusChange = (dose: Dose, index: number) => {
  if (dose.completed && !dose.actualDate) {
    dose.actualDate = dayjs();
  }
  if (dose.completed && !dose.doctor) {
    dose.doctor = '孙医生';
  }
  if (dose.completed && !dose.remarks) {
    dose.remarks = `基础疫苗${dose.name}`;
  }
};

const addProduct = (dose: Dose) => {
  currentDose.value = dose;
  showProductModal.value = true;
};

const removeProduct = (dose: Dose, product: Product) => {
  const index = dose.products.findIndex((p) => p.id === product.id);
  if (index !== -1) {
    dose.products.splice(index, 1);
    message.success('商品删除成功！');
  }
};

const handleProductSuccess = (products: Product[]) => {
  if (!currentDose.value) return;

  products.forEach((product) => {
    currentDose.value!.products.push({
      ...product,
      id: Date.now().toString() + Math.random().toString(36).slice(2, 11),
    });
  });

  showProductModal.value = false;
  message.success(`成功添加 ${products.length} 个商品！`);
};

const printOrder = () => {
  message.info('打印功能开发中...');
};

const saveOrder = () => {
  if (!selectedOrder.value) return;

  // 保存到本地存储
  const key = `vaccine_orders_${selectedPet.value?.id}`;
  localStorage.setItem(key, JSON.stringify(vaccineOrders.value));

  message.success('疫苗/驱虫单保存成功！');
};

const searchPets = () => {
  // 搜索功能已通过计算属性实现
};

// 生命周期
onMounted(() => {
  // 初始化数据
  // 默认选择第一个宠物
  if (pets.value.length > 0 && !selectedPet.value) {
    selectPet(pets.value[0]);
  }
});
</script>

<style scoped>
.vaccine-container {
  display: flex;
  height: 100vh;
  background-color: #f5f5f5;
}

.left-panel {
  display: flex;
  flex-direction: column;
  width: 300px;
  background: white;
  border-right: 1px solid #e8e8e8;
}

.pet-info-section {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.pet-tab {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  margin-bottom: 16px;
  background: #f0f0f0;
  border-radius: 4px;
}

.pet-name {
  font-weight: bold;
}

.pet-details {
  font-size: 14px;
}

.detail-row {
  display: flex;
  margin-bottom: 8px;
}

.label {
  width: 60px;
  color: #666;
}

.value {
  flex: 1;
  color: #333;
}

.vaccine-orders-section {
  flex: 1;
  padding: 16px;
}

.vaccine-orders-section h3 {
  margin-bottom: 16px;
  color: #333;
}

.orders-list {
  margin-bottom: 16px;
}

.order-item {
  padding: 12px;
  margin-bottom: 8px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  transition: all 0.3s;
}

.order-item:hover {
  background: #f6ffed;
  border-color: #1890ff;
}

.order-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.order-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
}

.order-name {
  font-weight: bold;
}

.order-time {
  font-size: 12px;
  color: #666;
}

.add-order-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.add-vaccine-btn {
  background: #52c41a;
  border-color: #52c41a;
}

.add-deworming-btn {
  background: #fa8c16;
  border-color: #fa8c16;
}

.center-panel {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.vaccine-form {
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.form-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 16px;
  margin-bottom: 24px;
  border-bottom: 1px solid #e8e8e8;
}

.header-left h2 {
  margin: 0 0 8px;
  color: #333;
}

.create-time {
  font-size: 14px;
  color: #666;
}

.vaccine-schedule {
  margin-bottom: 24px;
}

.vaccine-schedule h3 {
  margin-bottom: 16px;
  color: #333;
}

.schedule-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.dose-item {
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  transition: all 0.3s;
}

.dose-item.completed {
  background: #f6ffed;
  border-color: #52c41a;
}

.dose-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.dose-info {
  display: flex;
  flex-direction: column;
}

.dose-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.dose-date {
  font-size: 14px;
  color: #666;
}

.dose-status {
  display: flex;
  gap: 8px;
  align-items: center;
}

.status-text {
  font-size: 14px;
  color: #666;
}

.dose-details {
  padding-top: 12px;
  border-top: 1px solid #e8e8e8;
}

.detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.detail-row .label {
  width: 80px;
  font-size: 14px;
  color: #666;
}

.unit {
  margin-left: 8px;
  color: #666;
}

.products-section {
  padding-top: 16px;
  margin-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.section-header h4 {
  margin: 0;
  color: #333;
}

.total-section {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.total-label {
  margin-right: 8px;
  font-size: 16px;
  color: #333;
}

.total-amount {
  font-size: 20px;
  font-weight: bold;
  color: #1890ff;
}

.right-panel {
  width: 280px;
  overflow-y: auto;
  background: white;
  border-left: 1px solid #e8e8e8;
}

.no-selection,
.no-order-selected {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.empty-state {
  color: #999;
  text-align: center;
}

.empty-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.empty-state h3 {
  margin: 0 0 8px;
  color: #333;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}
</style>
